package com.ta.gulimall.gulimall.elasticsearch.service.impl;

import cn.hutool.json.JSONUtil;
import com.ta.gulimall.common.constant.ElasticsearchConstant;
import com.ta.gulimall.common.view.to.UpSpuInfoTo;
import com.ta.gulimall.gulimall.elasticsearch.config.ElasticsearchConfig;
import com.ta.gulimall.gulimall.elasticsearch.service.ElasticsearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public void productSave(List<UpSpuInfoTo> upSpuInfoToList) {
        BulkRequest bulkRequest = new BulkRequest();
        upSpuInfoToList.forEach(f -> {
            IndexRequest indexRequest = new IndexRequest(ElasticsearchConstant.PRODUCT_INDEX)
                    .id(f.getSkuId().toString())
                    .source(JSONUtil.toJsonStr(f), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        try {
            restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException("ElasticsearchServiceImpl保存spu商品信息出现异常", e);
        }
    }
}
